    var form = layui.form, table = layui.table, $ = layui.jquery, upload = layui.upload, id = getQueryVariable("id");

    $('#editor-form').find('input,textarea,select').attr('disabled',true);
    //表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "invoicenumber": "进入查看明细",
        })
    }
    form.render();

    //采购标签 判断是否有此角色
    let purchaseLabel = getAllRolesByCurr("ExportBusiness_Shipmentdetails_Purchase");
    //外销标签 判断是否有此角色
    let exportConcatLabel = getAllRolesByCurr("ExportBusiness_Shipmentdetails_ExportConcat");
    //日志标签 有权限:false 无权限:true
    let LogLabel = getAllRolesByCurr("LogLabel");

    let deleteAnnexIds = [];
    //产品明细数据
    let detailList = [];
    //费用数据
    let costList = [];
    //附件明细数据
    let annexList = [];
    //操作日志数据
    let operationLog = [];

    layer.ready(function () {
        //发票总额 无权限需隐藏
        if(purchaseLabel){
            $(".Authority-Label").hide();
        }
        //获取详情信息
        $.ajax({
            url:"carryDetail/detail?id="+id,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    if(null != res.data){
                        //主表数据
                        let vo =  res.data;
                        form.val("editor-form", {
                            "customerName" : vo.customerName,
                            "time" : vo.time,
                            "billNo" : vo.billNo,
                            "currency" : vo.currency,
                            "usdRate" : vo.usdRate,
                            "rmbRate" : vo.rmbRate,
                            "transitPlaceName" : vo.transitPlaceName,
                            "destinationName" : vo.destinationName,
                            "modeOfTransport" : vo.modeOfTransport,
                            "paymentMethodName" : vo.paymentMethodName,
                            "priceTermsName" : vo.priceTermsName,
                            "totalInvoiceAmount" : vo.totalInvoiceAmount,
                            "createDate" : vo.createDate,
                            "salesContractNo" : vo.salesContractNo,
                            "customerContractNo" : vo.customerContractNo,
                            "salesmanName" : vo.salesmanName,
                            "businessModelName" : vo.businessModelName,
                            "articleNumberDate" : vo.articleNumberDate,
                            "warehouseName" : vo.warehouseName,
                            "accountingPeriod" : vo.accountingPeriod,
                            "carryPlanNo" : vo.carryPlanNo,
                            "actualTimeDismissal" : vo.actualTimeDismissal,
                            "estimatedArrivalDate" : vo.estimatedArrivalDate,
                            "containerType" : vo.containerType,
                            "numberOfContainers" : vo.numberOfContainers,
                            "loadingTime" : vo.loadingTime,
                            "signingCompanyName" : vo.signingCompanyName,
                            "bankName" : vo.bankName,
                            "operator" : vo.operator,
                            "inspectionProgress" : vo.inspectionProgress,
                            "customerLevelName" : vo.customerLevelName,
                            "isDeclare" : vo.isDeclare,
                            "whetherCreditGuarantee" : vo.whetherCreditGuarantee,
                            "creditGuaranteeAmount" : vo.creditGuaranteeAmount
                        });

                        //产品明细数据
                        if(null != res.data.detailList && res.data.detailList.length > 0){
                            detailList = res.data.detailList;
                            table.reload('storageproductstableid',{data : detailList, limit : detailList.length});
                        }

                        //费用数据
                        if(null != res.data.costList && res.data.costList.length > 0){
                            costList = res.data.costList;
                            table.reload('costtableid',{data : costList});
                        }

                        //附件
                        if(null != res.data.annexList && res.data.annexList.length > 0){
                            annexList = res.data.annexList;
                            table.reload('attachmenttableid',{data : annexList});
                        }

                        //日志
                        if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                            //权限判断
                            if (!LogLabel) {
                                //有权限
                                operationLog = res.data.logList;
                            } else {
                                //无权限
                                operationLog = [];
                            }
                            table.reload('logtableid',{data:operationLog});
                        }

                    }
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    })


    //--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: detailList,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'saleContractNo', width: 120, title: '外销合同号'},
            {field: 'productCode', width: 120, title: '产品编码'},
            {field: 'specNo', width: 120, title: '规格编码'},
            {field: 'lotNo', width: 120, title: '批次'},
            {field: 'productNum', width: 120, title: '数量', totalRow: true},
            {field: 'fcUnitPrice', width: 80, title: '单价'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', totalRow: true},
            {field: 'warehouseReceiptNumber', width: 120, title: '入库单号'},
            {field: 'purchaseNo', width: 120, title: '采购单号'},
            {field: 'productSpecExplanation', width: 120, title: '规格说明'},
            {field: 'clientProductNo', width: 120, title: '客户货号'},
            {field: 'productCname', width: 120, title: '中文名称'},
            {field: 'productEname', width: 120, title: '英文名称'},
            {field: 'productCdesc', width: 120, title: '中文描述'},
            {field: 'productEdesc', width: 120, title: '英文描述'},
            {field: 'productUnitName', width: 120, title: '单位'},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
            {field: 'color', width: 120, title: '颜色'},
            {field: 'grossWeight', width: 120, title: '毛重'},
            {field: 'grossWeightSubtotal', width: 120, title: '毛重小计'},
            {field: 'netWeight', width: 120, title: '净重'},
            {field: 'netWeightSubtotal', width: 120, title: '净重小计'},
            {field: 'bulk', width: 120, title: '体积'},
            {field: 'bulkSubtotal', width: 120, title: '体积小计'},
            {field: 'totalTray', width: 120, title: '托数'},
            {field: 'trayNumber', width: 120, title: '每托量'},
            {field: 'boxAmount', width: 120, title: '件数'},
            {field: 'everyBoxAmount', width: 120, title: '每件数量'},
            {field: 'paymentPeriod', width: 120, title: '付款账期'},
            {field: 'costUnitPrice', width: 120, title: '成本单价'},
            {field: 'costSubtotal', width: 120, title: '成本小计'},
            {field: 'finishedProductCost', width: 120, title: '成品成本'},
            {field: 'accessoriesCost', width: 120, title: '配件成本'},
            {field: 'supplierName', width: 120, title: '供应商'},
            {field: 'clientContractNo', width: 120, title: '客户合同号'},
            {field: 'outerPackingLong', title: '外包装长', width: 120},
            {field: 'outerPackingWide', title: '外包装宽', width: 120},
            {field: 'outerPackingHeight', title: '外包装高', width: 120},
            {field: 'outerPackingSize', title: '外包装尺寸', width: 120},
            {field: 'outerPackingUnit', title: '外包装单位', width: 120},
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380,
        done:function (res, curr, count) {
            if(purchaseLabel){
                //采购标签:控制主表"发票总额",子表"单价"、"金额小计"
                //单价
                $("[data-field='fcUnitPrice']").css("display", "none");
                //金额小计
                $("[data-field='moneySubtotal']").css("display", "none");

            }
            if(exportConcatLabel){
                //外销标签:控制子表"成本单价"、"成本小计"、"成品成本"、"配件成本"、"供应商" 配件表 "成本单价"、"成本小计"、"供应商"
                //成本单价
                $("[data-field='costUnitPrice']").css("display", "none");
                //成本小计
                $("[data-field='costSubtotal']").css("display", "none");
                //成品成本
                $("[data-field='finishedProductCost']").css("display", "none");
                //配件成本
                $("[data-field='accessoriesCost']").css("display", "none");
                //供应商
                $("[data-field='supplierName']").css("display", "none");

            }
        }
    });
    //监听行单击事件
    table.on('row(storageproductstable)', function(obj){
        $("#hidden").show();
        let initParts = [];
        if(!isEmpty(obj.data.partsList)){
            initParts = obj.data.partsList;
        }
        table.render({
            elem: '#productsaselect'
            ,data:initParts
            ,toolbar: '#productsatoolbar'
            ,cols: [[
                {field: 'partsCode', title: '产品编码'}
                , {field: 'specNo', title: '规格编码'}
                , {field: 'proportionFinishedProducts', title: '成品比例'}
                , {field: 'partsFinishedProducts', title: '配件比例'}
                , {field: 'partsAmount', title: '配件数量'}
                , {field: 'costUnitPrice', width: 120, title: '成本单价'}
                , {field: 'costSubtotal', width: 120, title: '成本小计'}
                , {field: 'supplierName', width: 120, title: '供应商'}
                , {field: 'purchaseNo', width: 120, title: '采购单号'}
                , {field: 'productCname', title: '中文名称'}
                , {field: 'productEname', title: '英文名称'}
                , {field: 'grossWeight', title: '毛重'}
                , {field: 'netWeight', title: '净重'}
                , {field: 'bulk', title: '体积'}
            ]]
            ,id: 'productsatableid'
            ,page: false
            ,limit: Number.MAX_VALUE
            ,height:300
            ,done:function (res, curr, count) {
                if(exportConcatLabel){
                    //外销标签:控制子表"成本单价"、"成本小计"、"成品成本"、"配件成本"、"供应商" 配件表 "成本单价"、"成本小计"、"供应商"
                    //成本单价
                    $("[data-field='costUnitPrice']").css("display", "none");
                    //成本小计
                    $("[data-field='costSubtotal']").css("display", "none");
                    //供应商
                    $("[data-field='supplierName']").css("display", "none");

                }
            }
        });
    });

    //---费用
    table.render({
        elem: '#cost'
        , data: costList
        , toolbar: '#costtoolbar'
        , cols: [[
            {field: 'typeName', title: '费用类型'}
            , {field: 'amount', title: '金额',event:'amount',sort:true}
            , {field: 'contractNo', title: '外销合同号',sort:true}
            , {field: 'memo', title: '备注说明',sort:true}
        ]]
        , id: 'costtableid'
        , height: 380
        , page: false
        , limit: Number.MAX_VALUE
    });

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true, sort:true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            if(0 == annexList[i]["news"]){
                                //记录被删除的老的附件
                                deleteAnnexIds.push(id);
                            }
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName') {
            onLineFile(data.filePath);
        }
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    //---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //监听附件提交
    form.on('submit(form-element)', function (data) {

        let req = {};
        req["id"] = id;
        //该值取ModuleTypeEnum枚举类id
        req["type"] = 18;
        req["deleteAnnexIds"] = deleteAnnexIds;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        req["annexList"] = annexReqs;

        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"basicInformation/annex/add",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/ExportBusiness/shipmentdetails.jsp");
                        parent.intab("views/jsp/ExportBusiness/shipmentdetails.jsp", "出运明细")
                        parent.detab("views/jsp/ExportBusiness/tpl/viewshipmentdetails.jsp" + (id == '' ? '' : '?id=' + id));
                    }, 1000);
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    });
